package com.dyzx.hbb.common.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;

/**
 * 基础验证控制器
 * 
 * 功能说明：提供带有数据验证功能的基础控制器实现，扩展自BaseCustomController
 * 主要职责：
 * - 实现通用的新增、修改和删除操作，并添加数据验证逻辑
 * - 支持自定义数据验证处理
 * - 处理操作人、机构信息的自动填充
 * 
 * 设计意图：
 * 为需要数据验证的业务控制器提供通用实现，减少重复代码，提高系统一致性
 * 
 * @param <S> 服务类型，必须是 IService 的子类
 * @param <T> 实体类型
 * @param <Q> 查询参数类型
 * @param <V> 添加操作的请求体参数类型
 * @param <UV> 更新操作的请求体参数类型
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
public abstract class BaseValidController<S extends IService<T>, T, Q, V,UV> extends BaseCustomController<S,T, Q> {

    private static final String ORGAN_FIELD = "organId";
    private static final String OPRERATOR_FIELD = "operatorId";
    private final Class<T> entityClass;

    @SuppressWarnings("unchecked")
    protected BaseValidController() {
        this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }



    protected  abstract  T addValid(V entity);
    protected abstract T editValid(UV entity);

    /**
     * 新增
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result<Boolean> save(@Valid @RequestBody V entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        T entityCopy = createEntityCopy(entity);
        if (entityCopy == null) {
            return Result.error("创建实体对象失败");
        }
        Class<?> aClass = entityCopy.getClass();
     // 方案二：检查字段存在性（需要时使用）
        boolean hasOrganField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> ORGAN_FIELD.equals(f.getName()));
        boolean hasOperatorField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> OPRERATOR_FIELD.equals(f.getName()));
        Long userId = SecurityContextHolder.getUserId();
if(hasOperatorField) {
    BeanUtil.setProperty(entityCopy, OPRERATOR_FIELD, userId);

}

        if(hasOrganField){
            Long organId = SecurityContextHolder.getOrganId();
            BeanUtil.setProperty(entityCopy, ORGAN_FIELD, organId);

        }


        boolean save = getBaseService().save(entityCopy);
        return save? Result.ok() :Result.error("保存失败");
    }

    /**
     * 修改
     */
    @Operation(summary = "修改")
    @PutMapping
    public Result<Boolean> update(@Valid @RequestBody UV entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        T entityCopy = updateEntityCopy(entity);
        if (entityCopy == null) {
            return Result.error("创建实体对象失败");
        }

      /*  if (entityCopy.getId() == null) {
            return Result.error("id不能为空");
        }*/

        boolean data = getBaseService().updateById(entityCopy);
        return data? Result.ok() :Result.error("更新失败");
    }

    /**
     * 删除
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        if (id == null) {
            return Result.error("id不能为空");
        }
          Long organId = SecurityContextHolder.getOrganId();
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        T byId = getBaseService().getOne(queryWrapper.eq("id", id).eq("organ_id",organId).last("limit 1"));
        if (byId == null) {
            return Result.error("数据不存在");
        }

        boolean data = getBaseService().removeById(id);
        return data? Result.ok() :Result.error("删除失败");
    }
    private T createEntity() {
        T entityCopy;
        try {
            entityCopy = entityClass.getDeclaredConstructor().newInstance();

        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
        return entityCopy;
    }
    /**
     * 创建实体对象的副本
     * @param entity 请求体参数
     * @return 实体对象副本
     */
    private T createEntityCopy(V entity) {
        T entityCopy;
        try {
            if(addValid(entity) != null){
                entityCopy =addValid(entity);
            }else{
                entityCopy =entityClass.getDeclaredConstructor().newInstance();
                BeanUtil.copyProperties(entity, entityCopy);
            }
            System.out.println(entityCopy.toString());

        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
        return entityCopy;
    }
    private T updateEntityCopy(UV entity) {
        T entityCopy;
        try {
            if(editValid(entity) != null){
                entityCopy =editValid(entity);
            }else{
                entityCopy =entityClass.getDeclaredConstructor().newInstance();
            }
            entityCopy = entityClass.getDeclaredConstructor().newInstance();
            BeanUtil.copyProperties(entity, entityCopy);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
        return entityCopy;
    }
}
